// pages/seal/logistics/logistics.js
const config = require('../../../utils/config.js');

Page({
  data: {
    loading: true,
    error: '',
    logisticsInfo: null,
    courierNo: '',
    orderNo: ''
  },

  onLoad(options) {
    if (options.courierNo) {
      this.setData({
        courierNo: options.courierNo,
        orderNo: options.orderNo || ''
      });
      this.fetchLogisticsInfo(options.courierNo);
    } else {
      this.setData({
        error: '缺少物流单号',
        loading: false
      });
    }
  },

  // 获取物流信息
  fetchLogisticsInfo(courierNo) {
    this.setData({ loading: true, error: '' });

    wx.request({
      url: `${config.baseUrl}/seal/getCourierInfo`,
      method: 'GET',
      header: {
        'content-type': 'application/json',
        'Authorization': wx.getStorageSync('token') || ''
      },
      data: {
        courierNo: courierNo
      },
      success: (res) => {
        if (res.data.code === 200 && res.data.data && res.data.data.success) {
          const logisticsData = res.data.data.data.data;
          
          // 对物流轨迹按时间降序排列（最新的在前面）
          if (logisticsData.logisticsTraceDetailList && logisticsData.logisticsTraceDetailList.length > 0) {
            logisticsData.logisticsTraceDetailList.sort((a, b) => {
              // 使用time字段进行排序，如果time字段不存在则使用timeDesc
              const timeA = a.time || new Date(a.timeDesc).getTime();
              const timeB = b.time || new Date(b.timeDesc).getTime();
              return timeB - timeA; // 降序排列，最新的在前面
            });
          }
          
          this.setData({
            logisticsInfo: logisticsData,
            loading: false
          });
        } else {
          this.setData({
            error: res.data.data?.message || res.data.msg || '获取物流信息失败',
            loading: false
          });
        }
      },
      fail: (err) => {
        console.error('获取物流信息失败:', err);
        this.setData({
          error: '网络错误，请稍后重试',
          loading: false
        });
      }
    });
  },

  // 刷新物流信息
  onPullDownRefresh() {
    this.handleRefresh();
    wx.stopPullDownRefresh();
  },

  // 处理刷新按钮点击
  handleRefresh() {
    if (this.data.courierNo) {
      this.fetchLogisticsInfo(this.data.courierNo);
    }
  },

  // 复制物流单号
  handleCopyMailNo() {
    if (this.data.logisticsInfo && this.data.logisticsInfo.mailNo) {
      wx.setClipboardData({
        data: this.data.logisticsInfo.mailNo,
        success: () => {
          wx.showToast({
            title: '物流单号已复制',
            icon: 'success',
            duration: 1500
          });
        }
      });
    }
  },

  // 拨打电话
  handleCallPhone() {
    if (this.data.logisticsInfo && this.data.logisticsInfo.cpMobile) {
      wx.makePhoneCall({
        phoneNumber: this.data.logisticsInfo.cpMobile,
        fail: () => {
          wx.showToast({
            title: '拨号失败',
            icon: 'none',
            duration: 1500
          });
        }
      });
    }
  },

  // 返回上一页
  handleGoBack() {
    wx.navigateBack();
  }
});
